package com.syaccp.service.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.syaccp.request.SysUserRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.syaccp.constants.SysConfigConstants;
import com.syaccp.mapper.SysUserMapper;
import com.syaccp.model.SysMenu;
import com.syaccp.model.SysUser;
import com.syaccp.response.MenusResponse;
import com.syaccp.response.SysUserLoginResponse;
import com.syaccp.response.SystemAdminResponse;
import com.syaccp.service.SysMenuService;
import com.syaccp.service.UserService;
import com.syaccp.utils.JwtUtil;
import com.syaccp.utils.RedisCache;
import com.syaccp.utils.SecurityUtil;
import com.syaccp.vo.MenuTree;

import cn.hutool.core.collection.CollUtil;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author lixin
 * @since 2023-07-02
 */
@Service("userService")
public class UserServiceImpl implements UserService {

	@Override
	public List<SysUser> selectAll() throws SQLException {
		return sysUserMapper.selectAll();
	}
	@Override
	public SysUser selectByUserName(SysUser user) {
		QueryWrapper queryWrapper = new QueryWrapper();
		queryWrapper.eq("username",user.getUsername());
		SysUser sysUser = sysUserMapper.selectOne(queryWrapper);

		return sysUser;
	}

	@Autowired(required = false)
	private SysUserMapper sysUserMapper;

	@Autowired
	private RedisCache redisCache;
	@Resource
	private SysMenuService sysMenuService;


	@Override
	public int updateUser(SysUserRequest sysUser) {
		return sysUserMapper.updateUser(sysUser);
	}

	@Override
	public int addUser(SysUserRequest sysUser) {
		return sysUserMapper.addUser(sysUser);
	}

	@Override
	public List<SysUserRequest> userList(SysUserRequest sysUser) {
		return sysUserMapper.userList(sysUser);
	}

	@Override
	public PageInfo<SysUserRequest> pageGetUser(int index, SysUserRequest sysUser) {
		PageHelper.startPage(index, 2);
		return new PageInfo<SysUserRequest>(sysUserMapper.userList(sysUser));
	}


	@Override
	public SysUser loadUserByUsername(String username) {
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("username", username);
		SysUser sysUser = this.sysUserMapper.selectOne(queryWrapper);
		return sysUser;
	}

	@Override
	public SysUserLoginResponse login(SysUser sysUser, String ip) {

		// 把ip写到数据库sys_user中啊
		sysUser.setLoginIp(ip);
		sysUser.setLoginDate(new Date());
		sysUserMapper.updateById(sysUser);
		// 根据用户id创建一个token
		String token = JwtUtil.createJWT(sysUser.getId() + "");
		SysUserLoginResponse response = new SysUserLoginResponse();
		response.setToken(token);
		response.setId(sysUser.getId());
		response.setAccount(sysUser.getUsername());
		response.setRealName(sysUser.getName());
		String key = "login:" + sysUser.getId();

		redisCache.setCacheObject(key, sysUser);

		return response;
	}

	@Override
	public boolean logout(HttpServletRequest request, HttpServletResponse response) {
		SysUser sysUser = SecurityUtil.getLoginUser();

		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication != null) {
			new SecurityContextLogoutHandler().logout(request, response, authentication);
			String key = "login:" + sysUser.getId();
			redisCache.deleteObject(key);
			return true;
		} else {
			return false;
		}

	}

	@Override
	public SystemAdminResponse getInfoByToken() {
		SysUser sysUser = SecurityUtil.getLoginUser();
		SystemAdminResponse systemAdminResponse = new SystemAdminResponse();
		systemAdminResponse.setAccount(sysUser.getUsername());
		systemAdminResponse.setId(sysUser.getId());
		systemAdminResponse.setRealName(sysUser.getName());
		Integer roleId = sysUser.getRoleId();
		List<String> permList = CollUtil.newArrayList();
		systemAdminResponse.setRoles(roleId + "");
		if (new Integer(1).equals(roleId)) {
			permList.add("*:*:*");
			systemAdminResponse.setPermissionsList(permList);
		} else {
			systemAdminResponse.setPermissionsList(sysUser.getPermissions());
		}

		return systemAdminResponse;
	}

	@Override
	public Map<String, Object> getLoginPic() {
		Map<String, Object> map = new HashMap<>();
		// 背景图
		map.put("backgroundImage", SysConfigConstants.CONFIG_KEY_ADMIN_LOGIN_BACKGROUND_IMAGE);
		// logo
		map.put("logo", SysConfigConstants.CONFIG_KEY_ADMIN_LOGIN_LOGO_LEFT_TOP);
		map.put("loginLogo", SysConfigConstants.CONFIG_KEY_ADMIN_LOGIN_LOGO_LOGIN);
		// 轮播图
		List<String> bannerList = new ArrayList<>();
		bannerList.add("http://127.0.0.1:/images/7ccf9f4158794bf997d97b4e871dd34b4qy58l2fyg.png");

		map.put("banner", bannerList);
		return map;
	}

	@Override
	public List<MenusResponse> getMenus() {
		SysUser sysUser = SecurityUtil.getLoginUser();
		Integer roleId = sysUser.getRoleId();
		List<SysMenu> menuList = null;

		if (new Integer(1).equals(roleId)) {
			menuList = sysMenuService.findAllCatalogue();
		} else {
			Integer userId = sysUser.getId();
			menuList = sysMenuService.getMenusByUserId(userId);
		}

		// 组装前端对象
		List<MenusResponse> responseList = menuList.stream().map(e -> {
			MenusResponse response = new MenusResponse();
			BeanUtils.copyProperties(e, response);
//            response.setPid(e.getPid());
//            response.setSort(e.getSort());
//            response.setMenuType(e.getMenuType());
//            response.setComponent(e.getComponent());
//


			return response;
		}).collect(Collectors.toList());

		MenuTree menuTree = new MenuTree(responseList);
		return menuTree.buildTree();
	}

}
